export class GameLoop {
  constructor(update, render) {
    this.update = update;
    this.render = render;
    this.last = performance.now();
    this.acc = 0;
    this.fixed = 1000 / 60; // 60Hz 逻辑帧
    this._running = false;
    this._bus = null; // 可被注入，用于广播 tick
  }
  attachBus(bus) { this._bus = bus; }
  start() {
    if (this._running) return;
    this._running = true;
    const tick = () => {
      if (!this._running) return;
      const now = performance.now();
      let delta = now - this.last;
      this.last = now;
      this.acc += delta;
      while (this.acc >= this.fixed) {
        this.update(this.fixed);
        this.acc -= this.fixed;
        if (this._bus) this._bus.emit({ type: 'loop:tick', data: this.fixed });
      }
      this.render();
      requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }
  stop() { this._running = false; }
}